//
//  EditTimerView.swift
//  CrseAsst
//
//  Created by 申铭 on 2024/2/26.
//

import SwiftUI
import AlertToast

/// 2024-02-27 00:00:00
let kBaseTimestamp: TimeInterval = 1708963200

enum TimerType: String, CaseIterable {
    /// 正计时（指定时间段计时）
    case scheduleTime = "正计时"
    /// 计时器（单纯计时）
    case timer = "纯计时"
    /// 倒计时
    case countDown = "倒计时"
    
    var id: Int32 {
        switch self {
        case .scheduleTime: return 1
        case .timer: return 2
        case .countDown: return 3
        }
    }
    
    /// 根据ID获取type
    /// - Parameter id: id
    /// - Returns: TimerType
    static func getType(id: Int32) -> TimerType {
        switch id {
        case 1: return .scheduleTime
        case 2: return .timer
        case 3: return .countDown
        default: return .scheduleTime
        }
    }
}

struct EditTimerView: View {
    @Environment(\.presentationMode) var presentationMode
    
    private let viewModel = EditTimerViewModel()
    
    @State private var name: String = ""
    @State private var type: TimerType = .scheduleTime
    @State private var startTime = Date()
    @State private var endTime = Date()
    @State private var selectedColor = Color.pink
    /// 单位分钟
    @State private var duration: Int = 60
    
    @State private var isPresenting = false
    @State private var alertType: AlertToast.AlertType = .regular
    @State private var alertInfo: String = ""
    
    var body: some View {
        List {
            Section {
                TextField("计时器名称", text: $name)
                    .font(.title)
                    .multilineTextAlignment(.center)
                    .padding(EdgeInsets(top: 5, leading: 0, bottom: 0, trailing: 0))
                
                Picker("", selection: $type) {
                    ForEach(TimerType.allCases, id: \.self) {
                        Text($0.rawValue)
                    }
                }
                .pickerStyle(.segmented)
                .padding(EdgeInsets(top: 5, leading: 0, bottom: 5, trailing: 0))
                
                if type == .scheduleTime {
                    DatePicker(selection: $startTime, displayedComponents: .hourAndMinute) {
                        Text("开始时间")
                    }
                    
                    DatePicker(selection: $endTime, displayedComponents: .hourAndMinute) {
                        Text("结束时间")
                    }
                }
                
                if type == .countDown {
                    HStack {
                        Picker("", selection: $duration) {
                            ForEach((1...1440), id: \.self) {
                                Text("\($0)")
                            }
                            Text("分")
                        }
                        .pickerStyle(.wheel)
                        Text("分")
                    }
                }
            }
            .hideListRowSeperator()
            
            Section {
                ColorPicker("颜色", selection: $selectedColor)
            }
        }
        .toolbar {
            ToolbarItem {
                Button {
                    saveTimer()
                } label: {
                    Text("创建")
                }
            }
        }
        .toast(isPresenting: $isPresenting, duration: UIConst.hudDuration, alert: {
            AlertToast(type: alertType, title: alertInfo)
        })
    }
    
    private func saveTimer() {
        log.verbose("saveTimer")
        
        if name.isEmpty {
            log.warning("名称不能为空")
            isPresenting = true
            alertType = .error(.primary)
            alertInfo = "名称不能为空"
            return
        }
        
        let viewContext = PersistenceController.shared.container.viewContext
        
        let now = Date().timeIntervalSince1970
        let t = CATimer(context: viewContext)
        t.uuid = UUID().uuidString
        t.name = name
        t.type = type.id
        t.color = selectedColor.toHex()
        t.sort = now
        t.createTime = now
        t.updateTime = now
        
        if type == .scheduleTime {
            viewModel.setStartAndEndTime(timer: t, startTime: startTime, endTime: endTime)
        }
        
        t.duration = Double(duration * 60)
        
        withAnimation {
            do {
                try viewContext.save()
                isPresenting = true
                alertType = .complete(.green)
                alertInfo = ""
                
                FDelay(UIConst.hudDuration) {
                    self.presentationMode.wrappedValue.dismiss()
                }
            } catch {
                log.error("保存Timer出错:\(error)")
                isPresenting = true
                alertType = .error(.primary)
                alertInfo = "创建失败"
            }
        }
    }
    
}

#Preview {
    EditTimerView()
}
